package farmer.update.unit;

import pathfinding.grid.GridPath;

import farmer.update.building.Farm;
import farmer.update.building.LumberCamp;
import farmer.update.building.Windmill;
import farmer.render.doodad.Tree;
import farmer.update.building.Map;
import farmer.core.Building;
import farmer.core.Unit;

public abstract class Worker extends Unit{

	protected Building base;
	
	private Tree treeToHarvest = null;
	private Farm farmToHarvest = null;
	protected int ressource = 0;
	protected boolean isHarvesting = false;
	protected boolean isReturningToBase = false;
	private final int timeToHarvest = 4*1000;
	private int harvestTime = 0;
	
	
	public Worker(int x, int y, Building base) {
		super(x, y);
		this.base = base;
		this.speed = 0.1;
	}
	
	public void setTree(Tree tree){
		treeToHarvest = tree;
	}
	
	public void setFarm(Farm farm){
		farmToHarvest = farm;
	}
	
	public void update(int deltaTime){
		super.update(deltaTime);
		//Harvest a tree
		if(treeToHarvest != null){
			if(!isHarvesting){
				int x = (int) (posX/Map.cellWidth);
				int y = (int) (posY/Map.cellWidth);
				if(x == treeToHarvest.getX() && y == treeToHarvest.getY()){
					isHarvesting = true;
					harvestTime = timeToHarvest;
				}
			}
			if(isHarvesting){
				harvestTime -= deltaTime;
				if(harvestTime < 0){
					harvestTime = 0;
					isHarvesting = false;
					treeToHarvest.setHarvested();
					treeToHarvest = null;
					ressource = 1;
					isReturningToBase = true;
					GridPath path = map.getPath(this, base);
					setPath(path);
				}
			}
		}
		//Harvest a farm
		if(farmToHarvest != null){
			if(!isHarvesting){
				int x = (int) (posX/Map.cellWidth);
				int y = (int) (posY/Map.cellWidth);
				if(x == farmToHarvest.getX()+1 && y == farmToHarvest.getY()+2){
					isHarvesting = true;
					harvestTime = timeToHarvest;
				}
			}
			if(isHarvesting){
				harvestTime -= deltaTime;
				if(harvestTime < 0){
					harvestTime = 0;
					isHarvesting = false;
					farmToHarvest.setHarvested();
					farmToHarvest = null;
					ressource = 1;
					isReturningToBase = true;
					GridPath path = map.getPath(this, base);
					setPath(path);
				}
			}
		}
		//Return to base
		if(isReturningToBase){
			int x = (int) (posX/Map.cellWidth);
			int y = (int) (posY/Map.cellWidth);
			if(x == base.getX()+1 && y == base.getY()+2){
				isReturningToBase = false;
				if(base instanceof LumberCamp){
					LumberCamp lumber = (LumberCamp)base;
					lumber.addFreeWorker((farmer.render.unit.Worker)this);
					ressource = 0;
				}else if(base instanceof Windmill){
					Windmill mill = (Windmill)base;
					mill.addFreeWorker((farmer.render.unit.Worker)this);
					ressource = 0;
				}
			}
		}
	}

}
